
<template>
    <el-dialog :title="title" v-model="visible" append-to-body :lock-scroll="true" center custom-class="RegularPop"
        :close-on-click-modal="false">
        <div class="tenantInfos">
            <div class="tenant-image">
                <img v-if="form.photo != null && form.photo != ''" :src='form.photo' />
                <img v-else src='../../../assets/images/manage/zhaop.png' />
            </div>
            <div class="tenantInfos-right">
                <h3>{{ form.name }} <span style="color:#0096FF">{{ Status_dicText }}</span></h3>
                <ul>
                    <li><span>订单套餐</span>
                        <p>{{ comboName }}</p>
                    </li>
                    <li><span>用户数</span>
                        <p>{{ form.userNum}}</p>
                    </li>
                    <li><span>到期时间</span>
                        <p>{{ form.lastExpiredTime }}</p>
                    </li>
                    <li><span>客户经理</span>
                        <p>{{ form.sales }}</p>
                    </li>
                    <li><span>联系人</span>
                        <p>{{ form.contactBy }}</p>
                    </li>
                </ul>
            </div>
        </div>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="账号信息" name="0"></el-tab-pane>
            <el-tab-pane label="服务明细" name="1"></el-tab-pane>
        </el-tabs>
        <el-form :model="form" :rules="rules" ref="ruleFormRef" :inline="true" v-if="activeName == 0">
            <h1>账号信息</h1>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="注册时间">
                        <span>{{ form.createTime }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="注册渠道">
                        <span>{{ form.regChannel }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item label="域名">
                    <el-input v-if="!isView" v-model="form.hostName" placeholder="请输入" clearable />
                    <span v-if="isView">{{ form.hostName }}</span>
                </el-form-item>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="注册账号">
                        <span>{{ form.userName }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="设置密码">
                        <div class="setPW" v-if="!isView">
                            <el-input v-model="form.Pwd" placeholder="请输入" :readonly="readOnly" />
                            <span class="Change-password" @click="changePW">重置密码</span>
                        </div>
                        <span v-if="isView">{{ form.Pwd }}</span>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row>

                <el-col :span="12">
                    <el-form-item label="联系人" prop="contactBy">
                        <el-input v-if="!isView" v-model="form.contactBy" placeholder="请输入" clearable />
                        <span v-if="isView">{{ form.contactBy }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" prop="contactPhone">
                        <el-input v-if="!isView" v-model="form.contactPhone" placeholder="请输入" clearable />
                        <span v-if="isView">{{ form.contactPhone }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <div class="line"></div>
            <h1>客户信息</h1>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="租户名称" prop="name">
                        <el-input v-if="!isView" v-model="form.name" placeholder="请输入" clearable />
                        <span v-if="isView">{{ form.name }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="简称" prop="shortName">
                        <el-input v-if="!isView" v-model="form.shortName" placeholder="请输入" clearable />
                        <span v-if="isView">{{ form.shortName }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="租户类型" prop="type">
                        <el-select v-if="!isView" v-model="form.type" placeholder="租户类型" clearable>
                            <el-option v-for="dict in tenant_type" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                        <span v-if="isView">{{ form.type_dictText }}</span>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row>
                <el-col>
                    <el-form-item label="经营地址" required>

                        <span>{{ form.areaCode_dictText }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item label="详细地址">
                        <el-input v-if="!isView" v-model="form.address" placeholder="请输入" clearable />
                        <span v-if="isView">{{ form.address }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="电子邮箱" prop="email">
                        <el-input v-if="!isView" v-model="form.email" placeholder="请输入" clearable />
                        <span v-if="isView">{{ form.email }}</span>
                    </el-form-item>
                </el-col>


            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="照片">
                        <imageUpload ref="upload" v-model="form.photo" :limit="limit" :isShowTip='false' :fileSize="0.3"
                            :isdisabled="isDisabled" @UploadSuccess="UploadSuccess" @RemoveSuccess="RemoveSuccess"
                            @isChange="isChange" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item label="信息介绍" class="describe">
                    <el-input v-if="!isView" v-model="form.remark" type="textarea" show-word-limit maxlength="1000" />
                    <span v-if="isView">{{ form.remark }}</span>
                </el-form-item>
            </el-row>
            <div class="line"></div>
            <h1>订单套餐</h1>
            <div class="tenantComboDelete" v-if="!isView">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </div>
            <div class="tableList dialog-tableList">
                <el-table :data="tableData" v-loading="loading" style="width: 100%" border class="table-container"
                    stripe align="center" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" v-if="!isView"> </el-table-column>
                    <el-table-column label="序号" width="60" type="index"> </el-table-column>
                    <template v-for="(item, index) in tableHead" :key="index">
                        <el-table-column :prop="item.dataIndex" :label="item.title" :align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                    </template>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!isView">
                        <template #default="scope">

                            <a v-if="scope.row.serviceStatus == 1" @click="handleDisable(scope.row)" title="禁用">
                                <img src="../../../assets/images/manage/jy.png" alt="" />
                            </a>
                            <a v-if="scope.row.serviceStatus == 0 || scope.row.serviceStatus == 2"
                                @click="handleEnable(scope.row)" title="启用">
                                <img src="../../../assets/images/manage/qy.png" alt="" />
                            </a>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-form>
        <div class="tableList" v-if="activeName == 1">
            <el-table :data="serviceData" v-loading="loading" style="width: 100%" border class="table-container" stripe
                align="center" row-key="id" default-expand-all>
                <el-table-column label="序号" width="60" type="index"> </el-table-column>
                <el-table-column prop="label" label="服务名称" />
                <el-table-column prop="expiredTime" label="到期时间" />
                <el-table-column prop="serviceStatus" label="服务状态">
                    <template #default="scope">
                        <span v-if="scope.row.serviceStatus == 1" class="servicing">
                            服务中
                        </span>
                        <span v-else>
                            ----
                        </span>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog title="修改密码" custom-class="RegularPop el-dialog-s" v-model="innerVisible" append-to-body
            :lock-scroll="true" center :show-close="false">
            <el-form :model="form" :rules="rules" ref="passWordForm" :inline="true">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="新密码" prop="password">
                            <el-input v-model="form.password" placeholder="请输入9-12位以内，字母加数字组合" type="password"
                                maxlength="12" show-password clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="确认密码" prop="ConfirmPW">
                            <el-input v-model="form.ConfirmPW" placeholder="请再次输入密码" type="password" maxlength="12"
                                show-password clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="PwdClose">返回</el-button>
                    <el-button type="primary" @click="passWordSubmit()">确定</el-button>
                </span>
            </template>


        </el-dialog>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">返回</el-button>
                <el-button type="primary" v-if="!isView" @click="submitForm">确 定</el-button>
            </div>
        </template>

    </el-dialog>
</template>
<script setup>
import { addTenant, updateTenant, domain, getTenant, updateTenantComboStatus, getServiceItem, getComboList, delTenantCombo, resetTenantPwd } from '@/api/tenant/tenant'
import { getComboDic, calculateExpired } from '@/api/tenant/combo'
import { uploadCommon } from '@/mixins/ImageUploadMixin'

const { proxy } = getCurrentInstance();
const { tenant_type, tenant_reg_channel, tenant_status } = proxy.useDict("tenant_type", "tenant_reg_channel", "tenant_status");
const { UploadSuccess, RemoveSuccess, submit, formList, isChange } = uploadCommon.setup()
const title = ref("");
const visible = ref(false);
const readOnly = ref(true);
const comboName = ref('');
const areaCode = ref("");
const isDisabled = ref(false);
const innerVisible = ref(false);
const limit = ref(1);
const photo = ref('');
const isView = ref(false);
const activeName = ref('0');
const comboLists = ref({});
const Status_dicText = ref("");
const loading = ref(true);
const IMGtrue = ref(false);
const IMGStatus = ref(0)
const multiple = ref(true);
const ids = ref([]);
const single = ref(true);
const service = ref(false);
const total = ref(0);
const data = reactive({
    form: {
        Pwd: '*********',
        password: ''
    },
    queryParams: {
        tenantId: undefined,
        pageNum: 1,
        pageSize: 10,
    },
    rules: {
        name: [{ required: true, message: "租户名称不能为空", trigger: "blur" }],
        contactPhone: [
            { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        contactBy: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
        password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
        ConfirmPW: [{ validator: checkPwd2, trigger: "blur" }],
        shortName: [{ required: true, message: "简称不能为空", trigger: "blur" }],
        type: [{ required: true, message: "租户类型不能为空", trigger: "blur" }],
        // areaCode: [{ message: "经营地址不能为空", trigger: "blur" }],
        comboId: [{ required: true, message: "版本不能为空", trigger: "blur" }],

    },
    tableHead: [
        {
            dataIndex: 'name',
            title: '服务名称',

        },

        {
            dataIndex: 'sales',
            title: '客户经理',

        },

        {
            dataIndex: 'payAmount',
            title: '软件价格',

        },
        {
            dataIndex: 'payType_dictText',
            title: '缴费类型',

        },
        {
            dataIndex: 'paymentMethod_dictText',
            title: '支付方式',

        },
        {
            dataIndex: 'payTime',
            title: '支付时间',

        },
        {
            dataIndex: 'validityPeriod',
            title: '有效期',

        },
        {
            dataIndex: 'serviceStatus_dictText',
            title: '服务状态',

        },
    ],
    tableData: [],
    serviceData: []
});

const { queryParams, form, rules, pickerOptions, tableHead, tableData, serviceData } = toRefs(data);
function getAreaCode(code) {
    console.log("code", code);
    form.value.areaCode = code;
}
//
domain().then(res => {
    // console.log('yuming==', res)
})
//切换列表
function handleClick(tab, event) {
    if (tab.index == '0') {

    }
    if (tab.index == '1') {
        getServiceItem(form.value.id).then(res => {
            console.log('服务详细', res)
            if (res.code == 200) {
                serviceData.value = res.data
            }

        })
    }

}
/** 重置操作表单 */
function reset() {
    form.value = {};
    proxy.resetForm("ruleFormRef");
}
// 显示弹框
function view(row) {
    reset();
    visible.value = true;
    title.value = "查看详情";
    isDisabled.value = true;
    isView.value = true;
    const id = row.id;
    form.value = Object.assign({}, row);
    form.value.id = row.id
    areaCode.value = row.areaCode;
    form.value.type = row.type + ''
    form.value.Pwd = '********'
    getComboVos(id);


}
//修改
function edit(row) {
    console.log('row', row)
    reset();
    visible.value = true;
    title.value = "修改租户详情";
    isView.value = false;
    isDisabled.value = false
    const id = row.id
    form.value = Object.assign({}, row);
    areaCode.value = row.areaCode;
    form.value.type = row.type + ''
    form.value.Pwd = '********'
    formList.value = row.photo;
    console.log('回显的图', formList.value)
    getComboVos(id)
}

function getComboVos(id) {
    loading.value = true
    getTenant(id).then(res => {
        console.log('租户详情', res)
        if (res.code == 200) {
            // let comboVos = res.data.comboVos;
            // tableData.value = comboVos;
            // total.value = response.total;
            loading.value = false;
            form.value.type_dictText = res.data.tenantVo.type_dictText;
            form.value.lastExpiredTime = res.data.tenantVo.lastExpiredTime;
            form.value.userName = res.data.account;
            form.value.userNum = res.data.userNum
            let regChannel = res.data.tenantVo.regChannel + '';
            for (let i in tenant_reg_channel.value) {
                if (regChannel == tenant_reg_channel.value[i].value) {
                    form.value.regChannel = tenant_reg_channel.value[i].label
                }
            };
            let tenantStatus = res.data.tenantVo.status + '';
            for (let i in tenant_status.value) {
                if (tenantStatus == tenant_status.value[i].value) {
                    Status_dicText.value = tenant_status.value[i].label
                }
            };
            //
            queryParams.value.tenantId = res.data.tenantVo.id
            tenantCombo(queryParams.value)
        }
    })
}
function tenantCombo(query) {
    loading.value = true
    //获取租户套餐列表
    getComboList(query).then(res => {
        // console.log('租户套餐liebiao', res)
        if (res.code == 200) {
            tableData.value = res.rows;
            total.value = res.total;
            loading.value = false;
            let comboNames = [];
            for (let i in tableData.value) {
                if (tableData.value[i].serviceStatus == 1) {
                    comboNames.push(tableData.value[i].name)
                }
                comboName.value = comboNames.join(',')
            }
            //  console.log('comboName.value', comboName.value);
        }
    })
}
function handleDisable(row) {
    const status = 2;
    const tenantComboId = row.id
    queryParams.value.tenantId = row.tenantId;
    proxy.$modal.confirm('是否要禁用此套餐？').then(function () {
        return updateTenantComboStatus(tenantComboId, status)
    }).then(() => {
        //  tenantCombo(queryParams.value)
        getComboVos(queryParams.value.tenantId)
        proxy.$modal.msgSuccess("套餐已禁用");
    }).catch(() => { });

}
function handleEnable(row) {
    console.log('66666', row)
    const status = 1;
    const tenantComboId = row.id
    queryParams.value.tenantId = row.tenantId;
    proxy.$modal.confirm('是否要启此套餐？').then(function () {
        return updateTenantComboStatus(tenantComboId, status)
    }).then(() => {
        //  tenantCombo(queryParams.value)
        getComboVos(queryParams.value.tenantId)
        proxy.$modal.msgSuccess("套餐已启用");
    }).catch(() => { });

}
function getCombos() {
    getComboDic().then(res => {
        //  console.log('套餐列表', res)
        if (res.code == 200) {
            comboLists.value = res.data
        }

    })
}
function handleDelete() {
    const tenantComboIds = ids.value;
    if (service.value == false) {
        proxy.$modal.confirm('是否确认删除此套餐？').then(function () {
            return delTenantCombo(tenantComboIds);
        }).then(() => {
            tenantCombo(queryParams.value)
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => { });
    } else {
        proxy.$modal.confirm('套餐服务中不能删除！')
    }

}
//修改密码
function changePW() {

    innerVisible.value = true;
    form.value.password = '',
        proxy.resetForm("passWordForm");
    console.log('9999999', form.value)
}
function checkPwd2(rule, value, callback) {
    if (value === "" || value == undefined) {
        callback(new Error("请再次输入密码"));
    } else if (value != form.value.password) {
        callback(new Error("2次密码不一致"));
    } else {
        callback();
    }
}
/** 取消按钮 */
function cancel() {
    visible.value = false;

};
function handleUpdate(row) {

}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    let serviceType = selection.map(item => item.serviceStatus);
    for (let i in serviceType) {
        if (serviceType[i] != 1) {
            service.value = false

        } else {
            service.value = true
        }
    }
}
//
function onChangeCombo(val) {
    console.log('选中', val)
    const comboId = val
    calculateExpired(comboId).then(res => {
        if (res.code == 200) {
            form.value.lastExpiredTime = res.data[0] + ' - ' + res.data[1]
        }
    })
}

//提交
function submitForm() {
    proxy.$refs['ruleFormRef'].validate(valid => {
        if (valid) {
            if (form.value.id != undefined) {
                submit(formList => {
                    form.value.photo = formList
                    console.log('修改的图片', form.value.photo)
                    updateTenant(form.value).then(res => {
                        proxy.$modal.msgSuccess("修改成功");
                        visible.value = false;
                        proxy.$emit('refresh')
                    })
                })

            }
        } else {
            proxy.$modal.msgError("提交失败！");
            return false;
        }
    })
}
//密码取消
function PwdClose() {
    form.value.password = ''
    innerVisible.value = false;
}
//密码修改
function passWordSubmit() {
    proxy.$refs.passWordForm.validate(valid => {
        const data = {
            userName: form.value.userName,
            tenantId: form.value.id,
            password: form.value.password
        }

        if (valid) {
            resetTenantPwd(data).then(response => {
                proxy.$modal.msgSuccess("修改成功");
                innerVisible.value = false;
            });
        }
    });

}
getCombos();
defineExpose({
    view, edit
});
</script>
<style lang="scss" scoped>
.tenantInfos {
    background: #EFF0F1;
    border-radius: 4px;
    margin-top: 10px;
    padding: 10px 0;
    display: flex;

    .tenant-image {
        width: 60px;
        height: 60px;
        border-radius: 6px;
        margin-left: 10px;
        margin-top: 16px;

        img {
            object-fit: cover;
            width: 100%;
        }
    }

    .tenantInfos-right {
        font-size: 14px;
        color: #333;
        margin-left: 20px;

        h3 {
            span {
                margin-left: 10px;
            }
        }

        ul {
            display: flex;
            align-items: inherit;
            margin-top: 20px;

            li {
                line-height: 24px;
                border-right: 1px solid #DADADA;
                padding: 5px 0;
                min-width: 130px;

                span {
                    color: #666;
                    margin-left: 20%;
                }

                p {
                    margin-left: 20%;
                }
            }

            li:nth-child(1) {
                span {

                    margin-left: 0;
                }

                p {
                    margin-left: 0;
                }
            }

            li:nth-child(3) {
                min-width: 210px;
            }
        }
    }
}

.el-dialog-s {
    z-index: 11;
}
</style>
